package yhao.infra.feature.solr.local.core.group;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.params.GroupParams;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询条件
 */
public class GroupQueryInfo {
    private List<SolrGroupBean> groupFields;// 多个group查询
    private Integer groupLimit;// 每组group返回个数限制
    private boolean groupNGroups;

    public GroupQueryInfo(List<SolrGroupBean> groupFields, Integer groupLimit) {
        this.groupFields = groupFields;
        this.groupLimit = groupLimit;
        this.groupNGroups = true;
    }

    public Map<String, SolrGroupBean> getGroupFieldsMap() {
        if (groupFields == null) {
            return null;
        }
        Map<String, SolrGroupBean> beanMap = new HashMap<>();
        for (SolrGroupBean bean : groupFields) {
            beanMap.put(bean.getGroupField(), bean);
        }
        return beanMap;
    }

    public List<SolrGroupBean> getGroupFields() {
        return groupFields;
    }

    public Integer getGroupLimit() {
        return groupLimit;
    }

    public boolean isGroupNGroups() {
        return groupNGroups;
    }

    public void setGroupNGroups(boolean groupNGroups) {
        this.groupNGroups = groupNGroups;
    }

    public void makeGroupIndex(SolrQuery solrQuery) {
        solrQuery.add(GroupParams.GROUP, "true");
        if (groupFields != null) {
            for (SolrGroupBean groupField : groupFields) {
                solrQuery.add(GroupParams.GROUP_FIELD, groupField.getGroupField());
            }
        }
        if (groupLimit != null && groupLimit > 0) {
            solrQuery.add(GroupParams.GROUP_LIMIT, String.valueOf(this.getGroupLimit()));
        }
        if (groupNGroups) {
            solrQuery.add(GroupParams.GROUP_TOTAL_COUNT, String.valueOf(isGroupNGroups()));
        }
    }
}
